package com.sajhasite.service;

import java.util.Date;
import java.util.List;

import javax.inject.Inject;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sajhasite.dao.IPostDao;
import com.sajhasite.dao.IUserDao;
import com.sajhasite.domain.bean.ChildPostBean;
import com.sajhasite.domain.constant.CategoryType;
import com.sajhasite.domain.entity.ChildPost;
import com.sajhasite.domain.entity.Post;
import com.sajhasite.domain.entity.User;

/**
 * 
 * @author sbhandari
 *
 *
 *This interface/implementation will be containing all required services related to Posts and Child Posts
 */
@Service
@Transactional
public class PostService implements IPostService {
	

	@Inject
	private IPostDao postDao;
	@Inject
	private IUserDao userDao;
	
	
	
	public IUserDao getUserDao() {
		return userDao;
	}


	public void setUserDao(IUserDao userDao) {
		this.userDao = userDao;
	}


	public IPostDao getPostDao() {
    	return postDao;
    }	
	
	
	public void setPostDao(IPostDao postDao) {
    	this.postDao = postDao;
    }

	
	@Override
	public void addPost(Post post) {
		User user=this.getUser();
		post.setUser(user);
		post.setUpdatedTimestamp(new Date());
		post.setCreatedTimeStamp(new Date());
		this.postDao.saveOrUpdate(post);
	}

	@Override
	public void addChildPost(ChildPostBean childPostBean){
	Post post=this.postDao.loadPostById(Long.parseLong(childPostBean.getPostId()));
	ChildPost childPost=new ChildPost();
	childPost.setPost(post);
	childPost.setCreatedTimeStamp(new Date());
	childPost.setUpdatedTimeStamp(new Date());
	childPost.setUser(this.getUser());
this.postDao.saveOrUpdate(childPost);
		
	}

	@Override
	public List<Post> getLastNPosts(int n) {
		List<Post> posts=this.postDao.getLastNPosts(n);
		for(int i=0;i<posts.size();i++){
			System.out.println(posts.get(i).getChildPosts().size());
		}
		return posts;
		
	}

	@Override
	public Post getAllChildPostForPostId(Long postId) {
		Post post=	 (Post)this.postDao.loadPostById( postId);
		System.out.println("*******");
		if(post!=null){
			System.out.println(post.getChildPosts().size());		
			
		}
		else
			System.out.println("child not loaded");
			
		return post;
		//return null;//t this.postDao.getPostWithChildPost(postId);
	}

	@Override
	public CategoryType[] getCategoryList() {
		CategoryType[] categories=CategoryType.values();
		for(int i=0;i<categories.length;i++)
			System.out.println(categories[i].getDescription());
		return categories;
	}
	
	private User getUser(){
		User user=this.userDao.load(User.class, new Long(1));
		return user;
	}
	
	
}
